{block name="content"}
<script src="https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.full.min.js"></script>
<link rel="stylesheet" href="/assets/css/backend.min.css">
<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }


    .container {
        width: 90%;
        max-width: 1000px;
        background: rgba(255, 255, 255, 0.95);
        border-radius: 20px;
        box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
        padding: 30px;
        overflow: hidden;
    }

    header {
        text-align: center;
        margin-bottom: 30px;
    }

    h1 {
        color: #2c3e50;
        font-size: 2.5rem;
        margin-bottom: 10px;
        text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
    }

    .subtitle {
        color: #7f8c8d;
        font-size: 1.2rem;
        max-width: 600px;
        margin: 0 auto;
    }

    .controls {
        display: flex;
        justify-content: center;
        margin: 25px 0;
    }

    #exportBtn {
        background: #27ae60;
        color: white;
        border: none;
        padding: 15px 35px;
        font-size: 1.1rem;
        border-radius: 50px;
        cursor: pointer;
        transition: all 0.3s ease;
        align-items: center;
        box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
    }

    #exportBtn:hover {
        background: #2ecc71;
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(39, 174, 96, 0.6);
    }

    #exportBtn:active {
        transform: translateY(1px);
    }

    #exportBtn i {
        margin-right: 10px;
        font-size: 1.5rem;
    }

    .table-container {
        overflow-x: auto;
        border-radius: 15px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    }

    table {
        width: 100%;
        border-collapse: collapse;
        background: white;
    }

    table#table thead th {
        position: -webkit-sticky;
        position: sticky;
        top: 0;
        z-index: 10;
        background-color: green;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);

    th, td {
        padding: 15px 20px;
        text-align: left;
        border-bottom: 1px solid #ecf0f1;
    }

    th {
        background: #3498db;
        color: white;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    tr:nth-child(even) {
        background-color: #f8f9fa;
    }

    tr:hover {
        background-color: #e8f4fc;
        transition: background-color 0.2s;
    }

    .instructions {
        background: #f1f9ff;
        border-left: 4px solid #3498db;
        padding: 20px;
        margin-top: 30px;
        border-radius: 0 10px 10px 0;
    }

    .instructions h3 {
        color: #3498db;
        margin-bottom: 10px;
    }

    .instructions ol {
        padding-left: 20px;
    }

    .instructions li {
        margin-bottom: 10px;
        line-height: 1.6;
    }

    footer {
        text-align: center;
        margin-top: 30px;
        color: #7f8c8d;
        font-size: 0.9rem;
    }

    @media (max-width: 768px) {
        .container {
            padding: 15px;
        }

        h1 {
            font-size: 2rem;
        }

        th, td {
            padding: 10px 15px;
        }
    }
</style>
<div class="panel panel-default panel-intro">
    <div class="panel-heading">
        <div class="panel-lead"><em>{$year}年{$month}月排课表格</em></div>
    </div>
    <div class="panel-body">
        <div class="row">
            <div class="col-md-12">
                <form action="{:url('course/schedule/table')}" method="get" class="form-inline">
                    <div class="form-group" style="margin-left: 10px;">
                        <label for="publicwelfare_id">项目:</label>
                        <select class="form-control" id="publicwelfare_id" name="publicwelfare_id">
                            <option value="0">全部项目</option>
                            {volist name="publicwelfareList" id="vo"}
                            <option value="{$vo.id}" {if $publicwelfare_id==$vo.id}selected{/if}>{$vo.project_name}</option>
                            {/volist}
                        </select>
                    </div>
                    <!-- 新增社区筛选下拉框 -->
                    <div class="form-group" style="margin-left: 10px;">
                        <label for="community_code_filter">社区:</label>
                        <select class="form-control" id="community_code_filter" name="community_code_filter">
                            <option value="0">全部社区</option>
                            {php}
                                // 确保 $communityListForDropdown 变量存在且是数组
                                $safeCommunityListForDropdown = isset($communityListForDropdown) && is_array($communityListForDropdown) ? $communityListForDropdown : [];
                            {/php}
                            {volist name="safeCommunityListForDropdown" id="communityName" key="communityCode"}
                            <option value="{$communityCode}" {if condition="isset($community_code_filter) && (string)$community_code_filter === (string)$communityCode"}selected{/if}>{$communityName}</option>
                            {/volist}
                        </select>
                    </div>
                    <!-- 新增学科筛选下拉框 -->
                    <div class="form-group" style="margin-left: 10px;">
                        <label for="subject_id_filter">学科:</label>
                        <select class="form-control" id="subject_id_filter" name="subject_id_filter">
                            <option value="0">全部学科</option>
                            {php}
                                // 确保 $subjectListForDropdown 变量存在且是数组
                                $safeSubjectListForDropdown = isset($subjectListForDropdown) && is_array($subjectListForDropdown) ? $subjectListForDropdown : [];
                            {/php}
                            {foreach name="safeSubjectListForDropdown" item="subjectName" key="subjectId"}
                            <option value="{$subjectId}" {if condition="isset($subject_id_filter) && (string)$subject_id_filter === (string)$subjectId"}selected{/if}>{$subjectName}</option>
                            {/foreach}
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary" style="margin-left: 10px;">查询</button>
                    <a  id="exportBtn" href="" class="btn btn-success" style="margin-left: 10px;">导出Excel</a>
                </form>
            </div>
        </div>
        
        <div class="row" style="margin-top: 20px;">
            <div class="col-md-12">
                <div class="table-responsive">
<style>
    /* 基本样式 */
    .empty-row {
        display: none;
    }
    
    /* 切换按钮样式 */
    .toggle-empty-rows {
        margin-bottom: 10px;
    }
    
    /* 表格响应式布局 */
    .table-responsive {
        overflow-x: auto;
        position: relative;
        width: 100%;
        margin-bottom: 20px;
    }
    
    /* 表格基本样式 */
    .table-bordered {
        table-layout: fixed;
        width: 100%;
        border-collapse: collapse;
    }
    
    .table-bordered th,
    .table-bordered td {
        padding: 8px;
        vertical-align: middle;
        border: 1px solid #ddd;
    }
    
    /* 固定表头样式 */
    .table-header-fixed {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 100;
        background-color: #fff;
        border-bottom: 2px solid #ddd;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        display: none;
        overflow: hidden;
    }
    
    .table-header-fixed table {
        margin-bottom: 0;
        width: 100%;
        table-layout: fixed;
    }
    
    /* 兼容性样式 */
    .th-fixed {
        box-sizing: border-box;
    }
    
    /* 全屏模式样式增强 */
    :fullscreen .table-responsive {
        max-width: 100vw;
        height: auto;
    }
    table.table-bordered tr, table.table-bordered tr td {height:32px;line-height: 32px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;}
    .table-bordered > thead > tr > th, .table-bordered > thead > tr > td {
        border-bottom-width: 2px;
        background: green;
        color: #fff;
    }
    table.table-bordered tr, table.table-bordered tr td {
        height: 32px;
        line-height: 32px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        border: 1px solid #555;
    }
</style>
                    {if condition=" $subject_id_filter == '0' || $community_code_filter != '0'"}
                    <table id="table" class="table table-bordered table-striped" style="width:100%">
                        <thead>
                            <tr>
                                <th style="width:60px; background-color: #e8f5e9; color: #2e7d32; font-weight: 600;">日期</th>
                                <th style="width:160px; background-color: #e8f5e9; color: #2e7d32; font-weight: 600;">时间</th>
                                <th style="width:160px; background-color: #e8f5e9; color: #2e7d32; font-weight: 600;">社区</th>
                                {foreach name="allMonths" item="monthName" key="monthNum"}
                                <th style="background-color: #e8f5e9; color: #2e7d32; font-weight: 600;" data-month="{$monthNum}">{$monthName}</th>
                                {/foreach}
                            </tr>
                        </thead>
                        <tbody>
                            {php}
                            
                                // 定义颜色映射
                                $colorMap = [
                                    '1' => '#FFD700', // 音乐
                                    '2' => '#FF6347', // 舞蹈
                                    '3' => '#4682B4', // 书法
                                    '4' => '#32CD32', // 绘画
                                    '5' => '#9370DB', // 钢琴
                                    '6' => '#A0522D', // 太极
                                    '7' => '#FF69B4', // 剪纸
                                    '8' => '#20B2AA', // 中医
                                    '9' => '#CD853F', // 国画
                                    '10' => '#6495ED', // 生活
                                    '11' => '#00CED1', // 运动
                                    '12' => '#BA55D3', // 主持
                                ];
                            {/php}
                            
                            {foreach name="organizedTimeSlots" item="daySlots" key="dayKey"}
                                {foreach name="daySlots" item="timeSlot" key="timeRange"}
                                    {php}
                                        if($dayKey==16&&$timeSlot["id"]=="时段1"){
                                             if($targetCommunityDbName=="津头社区"){
                                                 $a=$timeSlot["id"];
                                             }
                                        }
                                        // 预先检查这一行是否有课程安排
                                        $hasAnyCourse = false;

                                        // 检查所有社区在任何月份是否有课程安排
                                        foreach ($communityList as $cid => $cname) {
                                            foreach ($allMonths as $mnum => $mname) {
                                                preg_match("/([0-9]+)年([0-9]+)月/Uisx", $mname, $matches);
                                                $mnum=(int)$matches[2];
                                                $k1 = $dayKey . '_' . $timeSlot['id'] . '_' . $cid . '_' . $mnum;
                                                $k2 = $dayKey . '_' . $timeRange . '_' . $cid . '_' . $mnum;
                                                $k3 = $matches[1]."_".preg_replace("/^0/","",$matches[2])."_".$dayKey . '_' . $timeSlot["id"] . '_'  . $cname;
                                                if (isset($tableData[$k1]) || isset($tableData[$k2])|| isset($tableData[$k3])) {
                                                    $hasAnyCourse = true;
                                                    break 2; // 找到课程，则跳出两层循环
                                                }
                                            }
                                        }
                                    {/php}

                                    {if condition="$hasAnyCourse"}
                                        {php}
                                            // 初始化静态变量跟踪上一个日期和时间段
                                            static $lastDay = null;
                                            static $lastTime = null;
                                            
                                            // 检查是否显示日期/时间单元格
                                            $showDateTime = ($lastDay !== $dayKey || $lastTime !== $timeRange);
                                            
                                            // 更新跟踪变量
                                            $lastDay = $dayKey;
                                            $lastTime = $timeRange;
                                        {/php}
                                        
                                        {php}
                                            // Ensure $communityList is defined for the volist loop
                                            if (!isset($communityList)) {
                                                $communityList = [];
                                            }
                                        {/php}
                                        {volist name="communityList" id="communityName" key="communityId"}
                                            <tr>
                                                {if condition="$showDateTime && $communityId == 1"}
                                                    <td rowspan="{:count($communityList)}">{$dayKey}号</td>

                                                {/if}
                                                <td>{$timeRange}</td>
                                                <td>{$communityName}</td>
                                                {foreach name="allMonths" item="monthName" key="monthNum"}
                                                    {php}
                                                        // 使用简化的键值格式yesyes
                                                        $slotId = is_array($timeSlot) ? $timeSlot['id'] : $timeRange;

                                                        // 基于控制器中的键值格式创建匹配逻辑
                                                        $dayInt = intval($dayKey);
                                                        $monthInt = intval($monthNum);
                                                        $communityName = $communityName; // 社区名称
                                                        $communityCode = $communityId; // 社区编码/ID
                                                        
                                                        // 获取社区编码和名称
                                                        if (isset($communityMapping[$communityId])) {
                                                            $communityName = $communityMapping[$communityId];
                                                        }
                                                        
                                                        // 尝试从communityDetailMapping获取更多信息
                                                        if (isset($communityDetailMapping[$communityId])) {
                                                            if (isset($communityDetailMapping[$communityId]['code'])) {
                                                                $communityCode = $communityDetailMapping[$communityId]['code'];
                                                            }
                                                            if (isset($communityDetailMapping[$communityId]['name'])) {
                                                                $communityName = $communityDetailMapping[$communityId]['name'];
                                                            }
                                                        }
                                                        
                                                        // 用来匹配控制器中键值的所有可能组合
                                                        $keys = [];
                                                        
                                                        // 修复键构建逻辑，确保使用正确的年份和月份
                                                        // 从月份名称中提取实际年份和月份数字
                                                        $actualMonth = $monthNum;
                                                        $actualYear = $year; // 默认使用当前年份
                                                        
                                                        // 如果月份名称是格式化的，如"2025年8月"，则提取实际年份和月份
                                                        if (preg_match('/(\d+)年(\d+)月/', $monthName, $matches)) {
                                                            $actualYear = intval($matches[1]);
                                                            $actualMonth = intval($matches[2]);
                                                        }
                                                        
                                                        // 添加缺失的格式化变量定义
                                                        $formattedMonth = sprintf("%02d", intval($actualMonth));
                                                        $formattedDay = sprintf("%02d", intval($dayInt));
                                                        
                                                        // 初始化调试变量
                                                        $debug = "";
                                                        
                                                        // 添加调试信息，显示当前使用的年份和月份
                                                        if ($actualYear . '_' . $actualMonth . '_' . $dayInt . '_' . $timeRange . '_' . $communityName=="2025_6_16_时段1_津头社区") {
                                                            $debug .= "\n当前参数: 年份=" . $actualYear . ", 月份=" . $actualMonth . ", 日期=" . $dayInt;
                                                        }
                                                        
                                                        // 尝试多种键值格式组合，确保使用正确的年份和月份
                                                        $keys[] = $actualYear . '_' . $actualMonth . '_' . $dayInt . '_' . $slotId . '_' . $communityName;

                                                        // 添加调试信息，显示尝试的键值
                                                        if ($communityName == '津头社区' || strpos($communityName, '津头') !== false) {
                                                            $debug .= "\n尝试的键值:";
                                                            foreach ($keys as $tryKey) {
                                                                $hasValue = isset($tableData[$tryKey]) ? '有值' : '无值';
                                                                $debug .= "\n" . $tryKey . " => " . $hasValue;
                                                                if (isset($tableData[$tryKey])) {
                                                                    $debug .= " (值: " . $tableData[$tryKey] . ")";
                                                                }
                                                            }
                                                            // 同时输出tableData中包含津头的所有键
                                                            $debug .= "\n\ntableData中包含津头的键值:";
                                                            foreach ($tableData as $key => $value) {
                                                                if (strpos($key, '津头') !== false || strpos($key, '1') !== false) {
                                                                    $debug .= "\n" . $key . " => " . $value;
                                                                }
                                                            }
                                                        }
                                                        // 社区名称而非社区编码
                                                        $keys[] = $dayInt . '_' . $timeRange . '_' . $communityDetailMapping[$communityName]['code']."_".$actualMonth;


                                                        // 尝试所有可能的键值格式
                                                        $courseId = '';
                                                        $matchedKey = '';
                                                        foreach ($keys as $testKey) {
                                                            if (isset($tableData[$testKey])) {
                                                                $courseId = $tableData[$testKey];
                                                                $matchedKey = $testKey;
                                                                break;
                                                            }
                                                        }


                                                        $courseName = $courseId ? (isset($courseList[$courseId]) ? $courseList[$courseId] : '未知课程') : '';
                                                        $courseDisplay = $courseName;
                                                        $bgColor = isset($colorMap[$courseId]) ? $colorMap[$courseId] : '';

                                                        // 生成显示和调试所需变量
                                                        $monthFormatted = sprintf("%02d", intval($monthNum));
                                                        $dayFormatted = sprintf("%02d", intval($dayKey));


                                                    {/php}
                                                    <td style="background-color: {$bgColor}; color: {$bgColor ? '#fff' : '#000'};"
                                                        title="{$courseDisplay}"
                                                        >
                                                        {$courseDisplay}
                                                    </td>
                                                {/foreach}
                                             </tr>
                                         {/volist}
                                    {/if}
                                {/foreach}
                            {/foreach}
                        </tbody>
                    </table>
                    {/if}
                </div>
            </div>
        </div>

        </div>

        <!-- 添加JavaScript来删除空的列和行 -->


        <script>
        // 确保jQuery已加载
        function waitForJQuery(callback) {
            if (typeof jQuery !== 'undefined') {
                callback();
            } else {
                console.log('等待jQuery加载...');
                setTimeout(function() {
                    waitForJQuery(callback);
                }, 100);
            }
        }

        // 等待jQuery加载完成后执行
        waitForJQuery(function() {
            $(document).ready(function() {
                // 延迟执行过滤，确保表格完全渲染
                setTimeout(function() {
                    console.log('开始执行表格过滤...');
                    filterEmptyColumnsAndRows();
                }, 500); // 延迟500毫秒
            });
        });

        function filterEmptyColumnsAndRows() {
            // 检查jQuery是否可用
            if (typeof jQuery === 'undefined') {
                console.error('jQuery未加载，无法执行过滤');
                return;
            }

            var $table = $('#table');
            if ($table.length === 0) {
                console.error('未找到表格元素 #table');
                return;
            }

            console.log('开始过滤空列和空行...');

            // 1. 找出所有月份列的索引（从第4列开始，前3列是日期、时间、社区）
            var $headerCells = $table.find('thead tr th');
            var monthColumns = [];

            $headerCells.each(function(index) {
                if (index >= 3) { // 跳过前3列
                    monthColumns.push({
                        index: index,
                        monthNum: $(this).data('month'),
                        monthName: $(this).text().trim(),
                        element: $(this)
                    });
                }
            });

            console.log('找到月份列：', monthColumns.length);

            // 2. 改进的月份列检查逻辑
            var emptyColumns = [];
            monthColumns.forEach(function(col) {
                var hasData = false;
                var cellCount = 0;
                var nonEmptyCells = 0;

                $table.find('tbody tr').each(function() {
                    var $cell = $(this).find('td').eq(col.index);
                    if ($cell.length > 0) {
                        cellCount++;
                        var cellText = $cell.text().trim();
                        var cellHtml = $cell.html().trim();

                        // 更严格的检查：排除常见的空值
                        if (cellText !== '' &&
                            cellText !== '-' &&
                            cellText !== '&nbsp;' &&
                            cellText !== ' ' &&
                            cellHtml !== '' &&
                            cellHtml !== '-' &&
                            cellHtml !== '&nbsp;' &&
                            !cellHtml.match(/^[\s\-&nbsp;]*$/)) {
                            hasData = true;
                            nonEmptyCells++;
                        }
                    }
                });

                console.log('月份列 ' + col.monthName + '：总单元格=' + cellCount + '，非空单元格=' + nonEmptyCells + '，有数据=' + hasData);

                if (!hasData) {
                    emptyColumns.push(col.index);
                }
            });

            console.log('需要删除的空列索引：', emptyColumns);

            // 3. 删除空的月份列（从后往前删除，避免索引变化）
            emptyColumns.sort(function(a, b) { return b - a; });

            // 添加安全检查：不要删除前3列和最后一列
            var $headerCells = $table.find('thead tr th');
            var totalColumns = $headerCells.length;
            var safeEmptyColumns = emptyColumns.filter(function(colIndex) {
                return colIndex >= 3 && colIndex < totalColumns - 1; // 保护前3列和最后一列
            });

            console.log('原始空列：', emptyColumns, '，安全过滤后：', safeEmptyColumns, '，总列数：', totalColumns);

            safeEmptyColumns.forEach(function(colIndex) {
                console.log('删除列索引：', colIndex, '，列标题：', $table.find('thead tr th').eq(colIndex).text().trim());

                // 删除表头
                var $headerCell = $table.find('thead tr th').eq(colIndex);
                if ($headerCell.length > 0) {
                    $headerCell.remove();
                }

                // 删除所有行的对应列
                $table.find('tbody tr').each(function() {
                    var $cell = $(this).find('td').eq(colIndex);
                    if ($cell.length > 0) {
                        $cell.remove();
                    }
                });
            });

            // 4. 改进的社区行检查逻辑
            var $rows = $table.find('tbody tr');
            var removedRows = 0;

            $rows.each(function() {
                var $row = $(this);
                var hasData = false;
                var cellCount = 0;
                var nonEmptyCells = 0;

                // 检查除了前3列（日期、时间、社区）之外的所有列
                $row.find('td').each(function(index) {
                    if (index >= 3) { // 跳过前3列
                        cellCount++;
                        var cellText = $(this).text().trim();
                        var cellHtml = $(this).html().trim();

                        // 更严格的检查：排除常见的空值
                        if (cellText !== '' &&
                            cellText !== '-' &&
                            cellText !== '&nbsp;' &&
                            cellText !== ' ' &&
                            cellHtml !== '' &&
                            cellHtml !== '-' &&
                            cellHtml !== '&nbsp;' &&
                            !cellHtml.match(/^[\s\-&nbsp;]*$/)) {
                            hasData = true;
                            nonEmptyCells++;
                        }
                    }
                });

                if (!hasData && cellCount > 0) {
                    var communityName = '';
                    var $cells = $row.find('td');

                    // 尝试不同的方式获取社区名称
                    if ($cells.length >= 3) {
                        communityName = $cells.eq(2).text().trim(); // 第3列
                    }
                    if (!communityName && $cells.length >= 2) {
                        communityName = $cells.eq(1).text().trim(); // 第2列
                    }
                    if (!communityName && $cells.length >= 1) {
                        communityName = $cells.eq(0).text().trim(); // 第1列
                    }

                    console.log('删除空行，社区：', communityName, '，总列数：', $cells.length, '，非空单元格：', nonEmptyCells);
                    $row.remove();
                    removedRows++;
                }
            });

            console.log('删除了 ' + removedRows + ' 个空行');

            // 5. 检查表格结构完整性
            var finalHeaderCount = $table.find('thead tr th').length;
            var firstRowCellCount = $table.find('tbody tr:first td').length;
            console.log('过滤后表头列数：', finalHeaderCount, '，第一行单元格数：', firstRowCellCount);

            if (finalHeaderCount !== firstRowCellCount) {
                console.warn('警告：表头和表体列数不匹配！');
            }

            // 6. 修复表格样式
            $table.find('thead tr th, tbody tr td').each(function() {
                var $cell = $(this);
                // 确保单元格有基本样式
                if (!$cell.attr('style') || $cell.attr('style').indexOf('background') === -1) {
                    if ($cell.is('th')) {
                        $cell.css({
                            'background-color': '#f8f9fa',
                            'border': '1px solid #dee2e6',
                            'padding': '8px',
                            'text-align': 'center'
                        });
                    } else {
                        $cell.css({
                            'border': '1px solid #dee2e6',
                            'padding': '8px',
                            'text-align': 'center'
                        });
                    }
                }
            });

            // 7. 更新rowspan（如果有的话）
            updateRowSpans();

            console.log('过滤完成');
        }

        function updateRowSpans() {
            var $table = $('#table');
            var $rows = $table.find('tbody tr');

            if ($rows.length === 0) return;

            // 重新计算日期列的rowspan
            var dateGroups = {};
            var currentDate = '';

            // 第一步：分析现有的行结构，正确识别每行的数据
            $rows.each(function(index) {
                var $row = $(this);
                var $cells = $row.find('td');

                var dateText = '';
                var timeText = '';
                var communityText = '';
                var otherCells = [];

                // 判断这一行的结构
                if ($cells.length >= 3) {
                    var firstCellText = $cells.eq(0).text().trim();

                    // 如果第一个单元格包含"号"，说明这是有日期的行
                    if (firstCellText.indexOf('号') !== -1) {
                        dateText = firstCellText;
                        timeText = $cells.eq(1).text().trim();
                        communityText = $cells.eq(2).text().trim();
                        currentDate = dateText; // 更新当前日期

                        // 收集其他列
                        for (var i = 3; i < $cells.length; i++) {
                            otherCells.push($cells.eq(i).html());
                        }
                    } else {
                        // 这是没有日期的行（被rowspan合并的行）
                        dateText = currentDate; // 使用当前日期
                        timeText = $cells.eq(0).text().trim(); // 第一列是时间
                        communityText = $cells.eq(1).text().trim(); // 第二列是社区

                        // 收集其他列
                        for (var i = 2; i < $cells.length; i++) {
                            otherCells.push($cells.eq(i).html());
                        }
                    }

                    // 记录每个日期的行
                    if (dateText !== '') {
                        if (!dateGroups[dateText]) {
                            dateGroups[dateText] = [];
                        }
                        dateGroups[dateText].push({
                            rowIndex: index,
                            $row: $row,
                            timeText: timeText,
                            communityText: communityText,
                            otherCells: otherCells,
                            hasDateCell: firstCellText.indexOf('号') !== -1
                        });
                    }
                }
            });

            // 第二步：重新构建表格结构
            var newTableBody = '';

            Object.keys(dateGroups).forEach(function(dateText) {
                var dateRows = dateGroups[dateText];
                var dateRowSpan = dateRows.length;

                dateRows.forEach(function(rowInfo, index) {
                    var rowHtml = '<tr>';

                    // 第一行显示日期（带rowspan）
                    if (index === 0) {
                        rowHtml += '<td rowspan="' + dateRowSpan + '">' + dateText + '</td>';
                    }

                    // 添加时间列
                    rowHtml += '<td>' + rowInfo.timeText + '</td>';

                    // 添加社区列
                    rowHtml += '<td>' + rowInfo.communityText + '</td>';

                    // 添加其他列
                    rowInfo.otherCells.forEach(function(cellHtml) {
                        rowHtml += '<td>' + cellHtml + '</td>';
                    });

                    rowHtml += '</tr>';
                    newTableBody += rowHtml;
                });
            });

            // 第三步：替换表格内容
            if (newTableBody !== '') {
                $table.find('tbody').html(newTableBody);
            }
        }
        </script>

    </div>
{/block}

{block name="script"}
{if condition=" $subject_id_filter != '0'"}
<div class="panel panel-default" style="margin-top: 20px;">
    <div class="panel-heading">
        <div class="panel-lead"><em>{$subjectListForDropdown[$subject_id_filter]}课程安排简表</em></div>
    </div>
    <div class="panel-body">
        <div class="table-responsive">
            <table id="table" class="table table-bordered" style="width:100%">
                <thead>
                    <tr>
                        <th style="width:40px">序号</th>
                        <th>时间</th>
                        <th>社区</th>
                        <th>课程</th>
                        <th>上课地址7777</th>
                    </tr>
                </thead>
                <tbody>
                    {php}
                        $simplifiedList = [];
                        foreach ($organizedTimeSlots as $dayKey => $daySlots) {
                            foreach ($daySlots as $timeRange => $timeSlot) {
                                foreach ($communityList as $communityId => $communityName) {
                                    foreach ($allMonths as $monthNum => $monthName) {
                                        $slotId = is_array($timeSlot) ? $timeSlot['id'] : $timeRange;
                                        $key = $dayKey . '_' . $slotId . '_' . $communityId . '_' . $monthNum;

                                        if (isset($tableData[$key]) && $tableData[$key] == $subject_id_filter) {
                                            // 确保年份是4位数字（20xx）
                                            $fullYear = 2000 + intval($year);

                                            // 格式化日期时间 (用于显示)
                                            $displayDateTime = sprintf(
                                                "%04d年%02d月%02d日 %s",
                                                $fullYear,
                                                intval($monthNum),
                                                intval($dayKey),
                                                $timeRange
                                            );

                                            // 创建标准格式的日期时间字符串用于排序 (YYYY-MM-DD HH:MM)
                                            $startTimeForSorting = explode('-', $timeRange)[0];
                                            $sortableDateTimeString = sprintf(
                                                "%04d-%02d-%02d %s",
                                                $fullYear,
                                                intval($monthNum),
                                                intval($dayKey),
                                                $startTimeForSorting
                                            );

                                            // 获取上课地址
                                            $address = isset($addressMapping[$communityId]) ? $addressMapping[$communityId] : '待定';

                                            $simplifiedList[] = [
                                                'displayDateTime' => $displayDateTime,
                                                'sortableDateTime' => $sortableDateTimeString,
                                                'community' => $communityName,
                                                'course' => $subjectListForDropdown[$subject_id_filter],
                                                'address' => $address
                                            ];
                                        }
                                    }
                                }
                            }
                        }


                    // 使用冒泡排序
                    $count = count($simplifiedList);
                    for ($i = 0; $i < $count - 1; $i++) {
                        for ($j = 0; $j < $count - 1 - $i; $j++) {
                            $timestampA = strtotime($simplifiedList[$j]['sortableDateTime']);
                            $timestampB = strtotime($simplifiedList[$j + 1]['sortableDateTime']);

                            if ($timestampA > $timestampB) {
                                // 交换位置
                                $temp = $simplifiedList[$j];
                                $simplifiedList[$j] = $simplifiedList[$j + 1];
                                $simplifiedList[$j + 1] = $temp;
                            }
                        }
                    }
                    {/php}
                    {volist name="simplifiedList" id="item" key="i"}
                    <tr>
                        <td>{$i}</td>
                        <td>{$item.displayDateTime}</td>
                        <td>{$item.community}</td>
                        <td>{$item.course}</td>
                        <td>{$item.address}</td>
                    </tr>
                    {/volist}
                </tbody>
            </table>
        </div>
    </div>
</div>
{/if}

{/block}





